package aplug;

import android.content.Context;
import android.support.multidex.MultiDex;

import com.amap.api.maps.MapsInitializer;

import org.changs.aplug.AplugManager;
import org.changs.aplug.simple.entry.OnTrimMemoryEvent;
import org.changs.s3.common.tools.NavTools;
import org.greenrobot.eventbus.EventBus;

import aplug.di.DaggerAppComponent;
import dagger.android.AndroidInjector;
import dagger.android.support.DaggerApplication;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;
import timber.log.Timber;

/**
 * Created by yincs on 2017/10/13.
 */

public class MyApp extends DaggerApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        //用一个字段表明是否进入了初始化界面。如果进入过了，直接在application里进行初始化
    }

    @Override
    protected void attachBaseContext(Context base) {
        MultiDex.install(this);
        super.attachBaseContext(base);
    }

    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        AplugManager.get().onCreate(new AplugManager
                .Config(this)
                .debug());

        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                Timber.d("RxJavaPlugins ErrorHandle throwable = [" + throwable + "]");
                throwable.printStackTrace();
//                if (throwable instanceof UndeliverableException) {
//                    Timber.e("UndeliverableException: ");
//                } else {
//                    if (throwable instanceof Exception)
//                        throw (Exception) throwable;
//                    throw new Exception(throwable);
//                }
            }
        });

        MapsInitializer.sdcardDir = NavTools.getMapRootDir(this).getAbsolutePath();
        return DaggerAppComponent.builder().application(this).build();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Timber.d("onTerminate() called");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        EventBus.getDefault().post(new OnTrimMemoryEvent(level));
//        Timber.d("onTrimMemory() called with: level = [" + level + "]");
//        Timber.d("onTrimMemory() called  " + System.currentTimeMillis());
//        try {
//            Thread.sleep(800);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//            Timber.d("onTrimMemory() InterruptedException");
//        }
//        Timber.d("onTrimMemory() called 1  "+ System.currentTimeMillis());
    }
}
